<?php

/**
 * 管理员模型类文件
 * 
 */
class Admin extends CActiveRecord {

    public $confirmPassword;
    public $oldPassword;
    public $password;

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function tableName() {
        return '{{admin}}';
    }

    public function rules() {
        return array(
            array('username', 'unique'),
            array('username, password, confirmPassword, oldPassword', 'required'),
            array('username, password', 'length', 'max' => 25),
            array('oldPassword', 'checkPass'),
            array('confirmPassword', 'compare', 'compareAttribute' => 'password', 'on' => 'create, update', 'message' => '两次密码不一致')
        );
    }

    public function relations() {
        return array(
        );
    }

    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'username' => '管理员名称',
            'password' => '新密码',
            'oldPassword' => '旧密码',
            'confirmPassword' => '二次密码'
        );
    }

    public function search() {

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id, true);
        $criteria->compare('username', $this->username, true);
        $criteria->compare('password', $this->password, true);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    public function beforeSave() {
        if (parent::beforeSave()) {
            if ($this->isNewRecord) {
                $this->salt = $this->generateSalt();
                $this->password = $this->hashPassword($this->password, $this->salt);
                return true;
            } else {
                $this->password = $this->hashPassword($this->password, $this->salt);
                return true;
            }
        }
        else
            return false;
    }

    public function validatePassword($password) {
        return $this->hashPassword($password, $this->salt) === $this->password;
    }

    public function hashPassword($password, $salt) {
        return md5($salt . $password);
    }

    protected function generateSalt() {
        return uniqid('', true);
    }

    public function checkPass($attribute) {
        if (isset($this->oldPassword)) {
            $model = Admin::model()->findByPk(user()->id);
            if ($this->hashPassword($this->oldPassword, $model->salt) === $model->password)
                return true;
            else
                $this->addError($attribute, '原密码输入错误!');
        }
    }

}